package com.portal.runner;

import com.portal.constant.RedisConst;
import com.portal.model.entity.Book;
import com.portal.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 库存数据预热到Redis中
 */
@Component
@Slf4j
public class StorageRunner implements CommandLineRunner {

    @Autowired
    private BookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 数据预热：
     * 1、项目启动，从mysql数据库查询图书库存，并保存到Redis中
     * 2、使用hash类型存储
     *     hset book:storage 1 1000
     */
    @Override
    public void run(String... args) throws Exception {
        if (!redisTemplate.hasKey(RedisConst.BOOK_STORAGE)) {
            List<Book> list = bookService.list();
            list.forEach(book -> {
                redisTemplate.opsForHash().put(
                        RedisConst.BOOK_STORAGE,
                        book.getId().toString(),
                        book.getStoreCount());
            });
            log.info("库存数据预热到Redis成功！");
        }
    }
}
